package com.game.chat_room;

import com.game.tools.LogTool;

import java.io.*;
import java.net.Socket;

public class ChatThread extends Thread{
    private Boolean isRunning = true;
    private Socket socket;

    public Boolean getRunning() {
        return isRunning;
    }

    public void setRunning(Boolean running) {
        isRunning = running;
    }

    public ChatThread(Socket socket){
        this.socket = socket;
        LogTool.outputLog("聊天连接线程已创建: " + this.toString());
    }

    /**
     * 推送信息
     *
     * @param out
     */
    public void out(String out) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            LogTool.outputLog("socket创建输出流outputStream");
            outputStream.write(out.getBytes("UTF-8"));
            LogTool.outputLog("socket.outputStream输出流，设置编码 utf-8");
            outputStream.flush();
            LogTool.outputLog("socket.outputStream输出流，强制输出，清空缓存区---------flush");
        } catch (Exception e) {
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void run() {
        try {
            while (isRunning) {

                LogTool.outputLog("等待信息输入...");
                /**
                 * 获取缓存字节输入流
                 */
                BufferedInputStream in = new BufferedInputStream(socket.getInputStream());

                /**
                 * 定义bytes
                 */
                byte[] clientCharStream = new byte[1024];

                /**
                 * 将缓存字节输入流读入字节数组
                 */
                in.read(clientCharStream);

                /**
                 * 字节 -> 字符串
                 *
                 * 编码：utf-8
                 * 长度：自适应
                 */
                String line = this.byteToString(clientCharStream);

                /**
                 * 推送信息
                 */
                LogTool.outputLog("推送信息中... : " + line);
                ChatThreadManager.getChartManager().publish(this, line);
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public void delete(){
        this.setRunning(false);
        this.stop();
        LogTool.outputLog("线程已关闭:" + this);
        //ChatThreadManager.ChatSocket_vector.remove(this);
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * byte[] -> String
     * 长度自适应
     * 编码格式：utf-8
     *
     * @param bytes
     * @return
     * @throws UnsupportedEncodingException
     */
    public String byteToString(byte[] bytes) throws UnsupportedEncodingException {
        int length = 0;
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] == 0) {
                length = i;
                break;
            }
        }

        return new String(bytes, 0, length, "utf-8");
    }

    @Override
    public String toString() {
        return  "\nChatThread{" +
                "isRunning=" + isRunning +
                ", socket=" + socket +
                '}';
    }

    /**
     * 判断是否连接关闭
     * @return
     */
    public Boolean isServerClose(){
        try{
            this.socket.sendUrgentData(0xFF);//发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
            return false;
        }catch(Exception se){
            return true;
        }
    }
}
